package com.googlecode.lookie.swing.tree.model;

import javax.swing.tree.TreeNode;

import com.googlecode.lookie.swing.tree.model.util.DeferredTreeNodeLoader;

public class DeferredTreeNodeModel
    extends LazyTreeNodeModel
{

    private static final long serialVersionUID = -1380444803949274359L;

    private boolean deferredEnabled;

    public DeferredTreeNodeModel( TreeNode root, TreeNodeProvider provider )
    {
        super( root, provider );
        deferredEnabled = true;
    }

    public boolean isDeferredEnabled()
    {
        return deferredEnabled;
    }

    public void setDeferredEnabled( boolean deferredEnabled )
    {
        this.deferredEnabled = deferredEnabled;
    }

    @Override
    public int getChildCount( Object parent )
    {
        if ( parent instanceof DeferredTreeNode )
        {
            DeferredTreeNode node = (DeferredTreeNode) parent;
            if ( node.isDeferred() && !node.isLoaded() )
            {
                if ( isDeferredEnabled() )
                {
                    DeferredTreeNodeLoader loader = new DeferredTreeNodeLoader( getProvider() )
                    {

                        @Override
                        public void postDeferred( DeferredTreeNode parent )
                        {
                            nodeStructureChanged( parent );
                        }

                    };
                    loader.load( node );
                }
                else
                {
                    node.fill( getProvider().getChildren( node ) );
                }
            }
        }
        return super.getChildCount( parent );
    }

}
